/**
 * *****************************************************************
 * @file    adt3102_rtc.c
 * @author  WuHao(hwu@andartechs.com.cn)
 * @version 1.0.0
 * @date    2020-11-09
 * @brief   
 *                 Copyright (c) 2020, Andar Technologies Inc.
 *                           www.andartechs.com 
 *
 * *****************************************************************
 */
/*------------------------------ include -------------------------------------*/
#include "adt3102_type_define.h"
#include "adt3102_rtc.h"
#include "rtc_ctype_map.h"
#include "pmu_ctype_map.h"
#include "rfc_ctype_map.h"
#include "adt3102_system.h"
#include "adt3102.h"


/*------------------------------ function ------------------------------------*/
/**
 * @brief   RTC init.
 * @param   enable: if set to 1,the RTC is enabled,don't write to this bit otherwise the current
 *                RTC value is reset to zero.
 * @param   reloadValue: The reloadValue is compared with the counter value generate an interrupt.
 * @param   rtcClock: Actually the clock frequency generated by 32K clock source, the uint is KHz.
 * @param   clkSource: select clk_32k source. Normally,
 *                  2'h0:32k RC.               -> RCSOR
 *                  2'h1:32k XO.               -> XOSOR
 *                  2'h2: div from clk_high    -> DIVHIGHSOR
 *                  , this is for normal function..
 * @return  function call example:  rtcInit(1, 1000, 32, RCSOR);.
 * @note
 */
void rtcInit(int32 enable, int32 reloadValue,int32 rtcClock,int32 clkSource)
{
    uint32 regVel;
    //RTC enable
    RTC->RTCCR   = enable;
    //control the masking of the interrupt that the RTC generates
    RTC->RTCIMSC = 1;

    regVel = PMU->pmu_clk_high_reg;
    regVel &= ~(pmu_clk_high_reg_ctrl_32k_clk_sel_mask << pmu_clk_high_reg_ctrl_32k_clk_sel_shift);
    regVel |= clkSource << pmu_clk_high_reg_ctrl_32k_clk_sel_shift;
    PMU->pmu_clk_high_reg = regVel  ;

    /*RW
    <5:0>:frequency calibration signal,32KHz for default setting '010111'. Calibretion range
    */
    //RFC->rf_rc32k_reg_reg = 0;
}


/**
 * @brief   start rtc timer.
 * @param   cycle_number: rtcClock*reloadValue.
 * @return  None.
 * @note
 */
void rtcTimerStart(uint32 cycle_number)
{
    //--- Option 1: Write RTCMR twice before going to SLEEP.
    //--- Because there may be a conflict between writing RTCMR and edge of clk_32k.
    //  int32 regVel;
    //  regVel = RTC->RTCDR;
    //  RTC->RTCMR = regVel + cycle_number;
    //  delayUs(1, HIGH_CLOCK_50M) ;
    //  RTC->RTCMR = regVel + cycle_number;

    //--- Option 2: Write RTCMR and then Write RTCLR.
    //--- Writing RTCLR has highest priority to writing RTCMR and edge of clk_32k,
    //--- And it will active all register.
    RTC->RTCMR = cycle_number; // rtcClock*reloadValue;//match value
    // After changing RTCMR, there MUST is a RTCLR command, to active MR register.
    RTC->RTCLR = 0x0 ;
}
